<script setup lang="ts">
import type { UniLoadMoreStatus } from '@uni-helper/uni-ui-types'

import { getPagedProjectsService } from '@/common/service/projects'
import type { Projects } from '@/common/types/projects'
import type { PagedParams } from '@/common/types/request'
import { NavigateItem, PageTitle } from '@/common/constants'
import skeleton from '@/common/skeleton/pages/projects.vue'

/**
 * 项目列表数据
 */
const projects = ref<Projects[]>([])

/**
 * 分页参数
 */
const pagedParams = ref<PagedParams>({
  pageNum: 1,
  pageSize: 5,
})

const total = ref<number>(0)

const loadingStatus = ref<UniLoadMoreStatus>('more')

const scrollTop = ref(0)

/**
 * 分页加载项目数据
 */
const getPagedProjects = async () => {
  const { data } = await getPagedProjectsService(pagedParams.value)
  total.value = data.total
  if (Array.isArray(data.item)) {
    projects.value = projects.value ? projects.value.concat(data.item) : data.item
  }
}

/**
 * 最大页码值
 */
const maxPageNum = computed(() => {
  return Math.ceil(total.value / pagedParams.value.pageSize)
})

/**
 * 加载更多
 */
const onLoadMore = async () => {
  // 判断是否已超出最大页码值
  if (pagedParams.value.pageNum >= maxPageNum.value) {
    loadingStatus.value = 'noMore'
    return showSimpleToast(NO_MORE_DATA)
  }

  // 让页码自增加一
  pagedParams.value.pageNum++

  loadingStatus.value = 'loading'
  await getPagedProjects()
  loadingStatus.value = 'more'
}

const { contentAreaHeight, tabBarHeight } = useLayoutInfo()

onLoad(() => {
  getPagedProjects()
})
</script>

<template>
  <!-- 自定义头部组件 -->
  <hope-nav-bar :title="PageTitle.PROJECT" />
  <!-- 滚动视图区域 -->
  <scroll-view
    class="projects-scroll flex" scroll-y :style="{
      height: `${contentAreaHeight - tabBarHeight}px`,
    }" :scroll-top="scrollTop" @scrolltolower="onLoadMore"
  >
    <!-- 顶部操作栏 包括 搜索栏以及导航项 -->
    <hope-top-actions :navigate-item="NavigateItem.MY_PROJECT" />
    <!-- 项目类标容器 -->
    <view class="projects-container">
      <uni-title type="h3" title="我的公益" align="center" />
      <!-- 项目组件 -->
      <template v-for="project in projects" :key="project.id">
        <template v-if="projects.length > 0">
          <hope-projects :project="project" />
        </template>
      </template>

      <template v-for="item in 5" :key="item">
        <skeleton />
      </template>
      <uni-load-more :status="loadingStatus" icon-type="circle" />
    </view>
  </scroll-view>
</template>

<style scoped lang="scss">
.projects {

  &-container {
    margin-top: 30rpx;
    padding: 30rpx;
    background-color: $color-white;
    border-top-left-radius: 30rpx;
    border-top-right-radius: 30rpx;

    &-title {
      text-align: center;

    }
  }
}
</style>
